﻿using BTS.Helpers.DataBaseHelper;
using BTS.Views;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static BTS.Models.LoginWindowModel;
using System.Windows;
using BTS.Common;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Input;

namespace BTS.ViewModels
{
    public partial class LoginViewModel:ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<string>? deviceType;
        [ObservableProperty]
        private ObservableCollection<string>? accountType;
        [ObservableProperty]
        private ObservableCollection<string>? accountName;
        [ObservableProperty]
        private ObservableCollection<string>? deviceNum;

        [ObservableProperty]
        private string? selectedAccountType;
        [ObservableProperty]
        private string? inputAccountName;
        [ObservableProperty]
        private string? inputDeviceNum;
        [ObservableProperty]
        private string? selectedDeviceType; 
        [ObservableProperty]
        private string? selectedDeviceNum;
        [ObservableProperty]
        private string? accountPwd;

        [ObservableProperty]
        private string? loginInfo;

        [ObservableProperty]
        private Color? foreColor;

        [RelayCommand]
        public void LoginIn()
        {
            eUserTypes SelUserTypes = (eUserTypes)Enum.Parse(typeof(eUserTypes), SelectedAccountType);
            UserInfo.AccountName = InputAccountName;
            UserInfo.DeviceType = (eDeviceTypes)Enum.Parse(typeof(eDeviceTypes), selectedDeviceType);
            UserInfo.Password = Helpers.StringSecurity.DESEncrypt(AccountPwd);
            UserInfo.AccountType = SelUserTypes;
            UserInfo.DeviceNo = InputDeviceNum;

            bool blLoginOK = false;
            if (SelUserTypes.Equals(eUserTypes.本地账户))
            {
                DataTable dataTable = DBHelper.DataBase.QuerySomething($" * FROM Login WHERE UserName1='{InputAccountName}' AND UserPSW1='{AccountPwd}'");
                if (dataTable.Rows.Count == 1)
                {
                    blLoginOK = true;
                    UserInfo.AccountAuth = (eUserAuths)Enum.Parse(typeof(eUserAuths), dataTable.Rows[0]["UserType1"].ToString());
                }
                else
                {
                    DataTable dt = DBHelper.DataBase.QuerySomething($" * FROM Login WHERE UserName1='{InputAccountName}'");
                    if (dt.Rows.Count >= 1)
                    {
                        LoginInfo = "输入账户密码错误! 提示：" + dt.Rows[0]["PSWTips"].ToString();
                        ForeColor = System.Windows.Media.Color.FromRgb(255, 0, 0);//red
                        return;
                    }
                    else
                    {
                        LoginInfo = "输入账户错误!";
                        ForeColor = System.Windows.Media.Color.FromRgb(255, 0, 0);//red
                        return;
                    }
                }
            }
            else if (SelUserTypes.Equals(eUserTypes.MES账户))
            {
                blLoginOK = false;
                UserInfo.AccountAuth = eUserAuths.操作员;
            }
            else if (SelUserTypes.Equals(eUserTypes.YXT账户))
            {
                blLoginOK = false;
                UserInfo.AccountAuth = eUserAuths.操作员;
            }
            else
            {
                blLoginOK = false;
                LoginInfo = ("未选择账户类型!");
                ForeColor = System.Windows.Media.Color.FromRgb(255, 0, 0);//red
                   // MessageView.Ins.MessageBoxShow("未选择账户类型!", Common.eMsgType.Error);
                return;
            }

            if (blLoginOK)
            {
                MainWindow mainWindow = new MainWindow(UserInfo);
                mainWindow.Show();

                SystemConfig.Ins.UserInfo = UserInfo;
                SystemConfig.Ins.SaveSystemConfig();
                LoginWindow.Close();
            }
        }

        [RelayCommand]
        public void Exit()
        {
            LoginWindow.Close();
        }
        [RelayCommand]
        public void ShowUserRegister()
        {
            //RegisterView registerView = new RegisterView();
            //registerView.ShowDialog();
            //GetUserName();
        }

        LoginView LoginWindow = null;
        public static User? UserInfo;

        private void GetAccountType()
        {
            AccountType = new ObservableCollection<string>();
            foreach (var item in Enum.GetValues(typeof(eUserTypes)))
            {
                AccountType.Add(item.ToString());
            }
        }
        private void GetAccountName()
        {
            AccountName = new ObservableCollection<string>();
            if (!DBHelper.DataBase.CreateNewDBFile(FilePaths.DataBasePath, ""))
                return;
            string strCreateLoginSQL = " ID  INTEGER   NOT NULL, " +
                   "UserName1 TEXT      NOT NULL UNIQUE, " +
                   "UserType1 TEXT    NOT NULL,    " +
                   "UserPSW1  TEXT      NOT NULL,  " +
                   "  PSWTips   TEXT (20),    " +
                   "DT1       TEXT,   " +
                   " PRIMARY KEY (" +
                   "ID AUTOINCREMENT" +
                " )";
            if (!DBHelper.DataBase.CreateTable("Login", strCreateLoginSQL))
                return;

            DataTable dataTable = DBHelper.DataBase.QueryAll("Login");
            if (dataTable.Rows.Count <= 0)
            {
                if (!DBHelper.DataBase.Insert("Login", $"(UserName1,UserPSW1,UserType1,PSWTips,DT1) VALUES ('Admin','123','{eUserAuths.管理员}','管理员通用密码','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"))
                {
                    MessageView.Ins.MessageBoxShow("Login表新增数据出错,请联系管理员",Common.eMsgType.Error);
                    return;
                }

                if (!DBHelper.DataBase.Insert("Login", $"(UserName1,UserPSW1,UserType1,PSWTips,DT1) VALUES ('Tester','123','{eUserAuths.操作员}','123','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')"))
                {
                    MessageView.Ins.MessageBoxShow("Login表新增数据出错,请联系管理员", Common.eMsgType.Error);
                    return;
                }
            }

            DataTable data = DBHelper.DataBase.QueryAll("Login");
            if (data.Rows.Count > 0)
            {
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    AccountName.Add(data.Rows[i]["UserName1"].ToString());
                }
            }
        }
        private void GetDeviceType()
        {
            DeviceType = new ObservableCollection<string>();
            foreach (var item in Enum.GetValues(typeof(eDeviceTypes)))
            {
                DeviceType.Add(item.ToString());
            }
        }

        public LoginViewModel(LoginView loginView)
        {
            LoginWindow = loginView;
            GetAccountType();
            GetAccountName();
            GetDeviceType();
            LoadAppConfig();
            UserInfo = new User();
        }

        private void LoadAppConfig()
        {
            try
            {
                if (SystemConfig.Ins.UserInfo != null)
                {
                    SelectedAccountType = SystemConfig.Ins.UserInfo.AccountType.ToString();
                    InputAccountName = SystemConfig.Ins.UserInfo.AccountName;
                    SelectedDeviceType = SystemConfig.Ins.UserInfo.DeviceType.ToString();
                    InputDeviceNum = SystemConfig.Ins.UserInfo.DeviceNo;
                }
            }
            catch (Exception ex)
            {
                MessageView.Ins.MessageBoxShow("Load UserInfo error!", Common.eMsgType.Error);
            }

        }


       

    }
}
